import { defineStore } from 'pinia';
import { UserInfo } from '@/util/auth/au_server_util';

const STORAGE_KEY = 'user_info';
const TOKEN_EXPIRE_TIME = 30 * 60 * 1000; // 30分钟

export const useUserInfoStore = defineStore('userInfo', {
	state: () => {
		// 从本地存储恢复数据
		const savedData = localStorage.getItem(STORAGE_KEY);
		const defaultState = {
			userInfo: {
				userSignin: null as UserInfo | null,
				userToken: null,
				lastRefreshTime: null,
				userId: null,
				signInLogId: null,
				accessToken: null,
				refreshToken: null
			}
		};

		if (savedData) {
			const parsedData = JSON.parse(savedData);
			const now = new Date().getTime();
			const savedTime = new Date(parsedData.userInfo.lastRefreshTime).getTime();
			
			// 检查是否过期
			if (now - savedTime < TOKEN_EXPIRE_TIME) {
				return parsedData;
			}
		}
		return defaultState;
	},
	actions: {
		setSigninInfo(userSignin: UserInfo, loginTime: string) {
			this.userInfo.userSignin = userSignin;
			this.userInfo.lastRefreshTime = new Date(loginTime);
			if (userSignin?.principal?.userInDb?.userId) {
				this.userInfo.userId = userSignin.principal.userInDb.userId;
			}
			this.saveToLocalStorage();
		},
		
		setTokens(accessToken: string, refreshToken: string) {
			this.userInfo.accessToken = accessToken;
			this.userInfo.refreshToken = refreshToken;
			this.userInfo.lastRefreshTime = new Date();
			this.saveToLocalStorage();
		},

		clearUserInfo() {
			this.userInfo = {
				userSignin: null,
				userToken: null,
				lastRefreshTime: null,
				userId: null,
				signInLogId: null,
				accessToken: null,
				refreshToken: null
			};
			localStorage.removeItem(STORAGE_KEY);
		},

		saveToLocalStorage() {
			localStorage.setItem(STORAGE_KEY, JSON.stringify(this.$state));
		},
		// 设置用户信息
		setUserInfo(isSuperManager,userDetail) {
			if(this.userInfo==null){
				this.userInfo={};
			}
			this.userInfo.isSuperManager = isSuperManager;
			this.userInfo.userDetail = userDetail;
		},
		setSigninLogId(logId){
			if(this.userInfo!=null){
				this.userInfo.signInLogId=logId;
			}
		},
		refreshToken(newToken){
			this.userInfo.userToken=newToken;
			this.userInfo.lastRefreshTime=new Date();
		}//
	}
});
